<!--
 * @Author: your name
 * @Date: 2021-08-30 20:39:23
 * @LastEditTime: 2021-09-12 13:45:25
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bigdate\src\components\Drawer\Drawer.vue
-->
<template>
    <div class="upload">
        <input
            ref="inputRef"
            type="file"
            accept=".xlsx,.xls"
            @change="handleInputClick"
        />
        <Button @click="ClickImp">
            <slot></slot>
        </Button>
    </div>
</template>

<script lang="ts">
import { defineComponent, unref, ref } from 'vue'
import { Button } from 'ant-design-vue'
/**
 *
 *
 * 一键导入Excel
 *
 */
import XLSX from 'xlsx'

interface MateOpts {
  sheetName: String;
}
interface ExcelData {
  header: string[];
  results: any;
  meta: MateOpts;
}
interface BasicColumn {
  title: String;
  dataIndex: String;
}
export default defineComponent({
    name: 'Impxlsx',
    components: { Button },
    emits: {
        success: (val) => val,
    },
    //   如果不想使用props 可以使用_代替
    setup(_, { emit }) {
        const inputRef = ref<HTMLInputElement | null>(null)
        const loadingRef = ref<Boolean>(false)
        // 可以使用以下方式设置类型
        const tableListRef = ref<
      {
        columns?: any[];
        dataSource?: any[];
        title?: String;
      }[]
    >([])
    // 数据过滤
        const filterDate = (datas) => {
            // 表处理 又可能是Sheet1,Sheet2
            for (const items of datas) {
                let {
                    header,
                    meta: { sheetName },
                    results,
                } = items
                let columns: BasicColumn[] = []
                for (const title of header) {
                    columns.push({
                        title,
                        dataIndex: title,
                    })
                }
                tableListRef.value.push({
                    title: sheetName,
                    dataSource: results,
                    columns,
                })
            }
            emit('success', tableListRef.value)
        }
        // 获取头部标签
        const getHeaderRow = (sheet: XLSX.WorkSheet) => {
            if (!sheet || !sheet['!ref']) return []
            const headers: string[] = []
            // A3:B7=>{s:{c:0, r:2}, e:{c:1, r:6}}
            const range = XLSX.utils.decode_range(sheet['!ref'])

            const R = range.s.r
            /* start in the first row */
            for (let C = range.s.c; C <= range.e.c; ++C) {
                /* walk every column in the range */
                const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
                /* find the cell in the first row */
                let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
                if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
                headers.push(hdr)
            }
            return headers
        }
        // 获得excel数据
        const getExcelData = (workbook: XLSX.WorkBook) => {
            const excelData: ExcelData[] = []
            for (const sheetName of workbook.SheetNames) {
                const worksheet = workbook.Sheets[sheetName]
                const header: string[] = getHeaderRow(worksheet)
                const results = XLSX.utils.sheet_to_json(worksheet)
                excelData.push({
                    header,
                    results,
                    meta: {
                        sheetName,
                    },
                })
            }
            return excelData
        }
        // 读取excel数据
        function readerData(rawFile) {
            loadingRef.value = true
            return new Promise((resolve, reject) => {
                const reader = new FileReader()
                reader.onload = async (e) => {
                    try {
                        const data = e.target && e.target.result
                        const workbook = XLSX.read(data, { type: 'array' })
                        const excelData = getExcelData(workbook)

                        filterDate(excelData)
                        resolve('')
                    } catch (err) {
                        reject(err)
                    } finally {
                        loadingRef.value = false
                    }
                }
                reader.readAsArrayBuffer(rawFile)
            })
        }
        //   使用异步 函数 函数不能是箭头函数
        //   将路径 传进去 rawFile
        async function upload(rawFile) {
            const inputRefDom = unref(inputRef)
            if (inputRefDom) {
                // fix can't select the same excel
                inputRefDom.value = ''
            }
            await readerData(rawFile)
        }
        //   触发器 获取路径
        const handleInputClick = (e) => {
            const files = e && (e.target as HTMLInputElement).files
            const rawFile = files && files[0] // only setting files[0]
            if (!rawFile) return
            upload(rawFile)
        }
        //   上传
        const ClickImp = () => {
            const inputRefDom = unref(inputRef)
            inputRefDom && inputRefDom.click()
        }
        return {
            handleInputClick,
            ClickImp,
            inputRef,
        }
    },
})
</script>

<style lang="less" scoped>
.upload {
  input {
    position: absolute;
    visibility: hidden;
    z-index: -1;
  }
}
</style>
